package zkclient;

import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.exception.ZkException;

import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * Created by Lenovo on 2018/11/20.
 */
public class LockImpl extends ZkAbstrackLock{

    private CountDownLatch cdl = null;
    @Override
    protected boolean tryLock() {
        try {
           /* if(!zkClient.exists(node)) {
                zkClient.createPersistent(node);
            }*/
            zkClient.createEphemeral(node);
            return true;
        }catch (ZkException e){
            return false;
        }

    }

    @Override
    protected void waitforLock() {
        IZkChildListener listener  = new IZkChildListener() {
            public void handleChildChange(String parentNode, List<String> childLists) throws Exception {
                cdl.countDown();
            }
        };

        zkClient.subscribeChildChanges(node, listener);
        if(zkClient.exists(node)){
            cdl = new CountDownLatch(1);
            try {
                cdl.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        zkClient.unsubscribeChildChanges(node, listener);
    }
}
